/*
 * @Author: jiutian
 * @Date: 2023-02-07 14:07:05
 * @LastEditTime: 2023-02-11 11:08:13
 * @LastEditors:
 */
// const ws = require("nodejs-websocket");
// const chalk = require("chalk");
// const PORT = 6580;

// var server = ws
//   .createServer(function (conn) {
//     conn.on("text", function (str) {
//       let { replyer, sender, text, id } = JSON.parse(str);
//       let sql = "insert into message set ?";
//       let sqlVal = {
//         sender_id: sender.id,
//         replyer_id: replyer.id,
//         context: text,
//       };
//       db.query(sql, sqlVal, (err, result) => {
//         if (err) return conn.sendText(JSON.stringify({ code: 400, msg: err }));
//         if (result.affectedRows !== 1)
//           return conn.sendText(JSON.stringify({ code: 400, msg: "系统错误" }));
//         conn.sendText(
//           JSON.stringify({
//             code: 200,
//             msg: "成功",
//             data: id,
//           })
//         );
//       });
//     });
//     conn.on("close", function (code, reason) {
//       // console.log(code, reason);
//       // console.log("Connection closed");
//     });

//     conn.on("error", function (err) {
//       console.log(chalk.red(err));
//     });
//   })
//   .listen(PORT);

//创建一个WebSocket服务器，在8080端口启动
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 6580 });
const db = require("../db");
const chalk = require("chalk");
const { formatTime } = require("../utils/index");

server.on("connection", function connection(ws, req) {
  // const ip = req.socket.remoteAddress;
  // const port = req.socket.remotePort;
  // const clientName = ip + ":" + port;
  ws.clientNameId = req.url.split("/")[1];
  // console.log(server.clients);
  server.clients.forEach((v) => {
    // console.log(v.clientNameId);
  });
  // console.log("%s is connected ", clientName);
  ws.on("message", function incoming(message) {
    let msg = JSON.parse(message.toString());

    let { replyer, sender, text, id } = msg;
    let sql = "insert into message set ?";
    let sqlVal = {
      sender_id: sender.id,
      replyer_id: replyer.id,
      context: text,
    };

    server.clients.forEach(function each(client) {
      if (
        client.readyState === WebSocket.OPEN &&
        client.clientNameId == sender.id
      ) {
        sqlVal.is_read = "1";
      }
    });

    db.query(sql, sqlVal, async (err, result) => {
      if (err)
        return ws.send(JSON.stringify({ code: 400, msg: err, data: id }));
      if (result.affectedRows !== 1)
        return ws.send(
          JSON.stringify({ code: 400, msg: "系统错误", data: id })
        );
      ws.send(
        JSON.stringify({
          code: 200,
          msg: "成功",
          data: id,
        })
      );

      for (let client of server.clients) {
        if (
          client.readyState !== WebSocket.OPEN &&
          client.clientNameId == sender.id
        ) {
          let messageObj = {
            id,
            senderId: sender.id,
            replyerId: replyer.id,
            context: text,
            createTime: formatTime(Date.now(), "YYYY-MM-DD HH-mm:ss"),
          };

          client.send(JSON.stringify(messageObj));
        }
      }
    });
  });

  ws.on("error", (error) => {
    console.log(chalk.red(error));
  });
});

function getNoRead(authId, userId) {
  return new Promise((resolve, reject) => {
    let sql =
      "select count(*) as count from message where is_read=0 and sender_id=? and replyer_id=? and status=1";
    db.query(sql, [userId, authId], (err, result) => {
      if (err) return reject(err);
      resolve(result[0].count);
    });
  }).catch((err) => {
    console.log(chalk.red(err));
  });
}
